package com.huatech.core.amqp;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.huatech.core.domain.User;

//@Component
public class UserProducer implements RabbitTemplate.ReturnCallback/**, RabbitTemplate.ConfirmCallback */{

	private static final Logger LOGGER = LoggerFactory.getLogger(UserProducer.class);
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@PostConstruct
	private void init() {
		// 启用事务模式,不能开确认回调
		//rabbitTemplate.setConfirmCallback(this);
		rabbitTemplate.setReturnCallback(this);
		rabbitTemplate.setChannelTransacted(true);
		//rabbitTemplate.setMandatory(mandatory);
	}

	@Transactional(transactionManager = "rabbitTransactionManager")
	public void send(User user) {
		LOGGER.info("Sender : {}", user.toString());
		CorrelationData cd = new CorrelationData(user.getUuid());
		rabbitTemplate.convertAndSend(RabbitConstant.EXCHANGE_DIRECT, RabbitConstant.QUEUE_USER, user, cd);
	}

//	@Override
//	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//		System.out.println("id:" + correlationData.getId() + ", msg:" + correlationData.getReturnedMessage());
//		LOGGER.info("correlationData: {}, ack:{}, cause:{}", correlationData, ack, cause);
//		if (!ack) {
//			LOGGER.info("异常处理....");
//		} else {
//			LOGGER.info("正常处理....");
//		}
//	}

	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
		LOGGER.info("returnCallback exchange:{}, routingKey:{}, replyCode:{},  replyText: ", exchange, routingKey,
				replyCode, replyText);
	}

}
